import useSyncState from '@/views/hooks/useSyncState';
import styled from '@emotion/styled';
import { Button, Col, Form, Row, Select, Slider } from 'antd';
import { t } from 'i18next';
import React, { useEffect, useRef, useState } from 'react';
import AudioAnalyser from './libs/AudioAnalyser';

interface SpeakerConfigureProps {
	audioOutput: MediaDeviceInfo[];
	mode: 'audio' | 'video' | 'speaker';
	selectKey: string;
	defaultDevice: MediaDeviceInfo | undefined;
	onOk: () => void;
	onCancel: () => void;
	onSelect: (id: string | undefined) => void;
}

interface DeviceInfo {
	value: string;
	label: string;
}

const Submit = styled.div`
	padding-top: 10px;
	text-align: right;
	.ant-btn-default {
		background-color: #fff;
	}
	.ant-btn-primary {
		margin-left: 8px;
	}
`;

const SpeakerConfigure = (props: SpeakerConfigureProps) => {
	const { audioOutput = [], selectKey = '3', defaultDevice = undefined, onCancel, onOk, onSelect } = props;

	const [form] = Form.useForm();

	const [speakerVol, setSpeakerVol] = useState<number>(50);
	const [selectedID, setSelectedID] = useSyncState<string | undefined>('default');

	const [isPlay, setPlay] = useState<boolean>(false);

	const audioRef = useRef<HTMLAudioElement | null>(null);

	const audioAnalyserRef = useRef<AudioAnalyser | null>(null);

	const [speakerDevice, setSpeakerDevice] = useState<DeviceInfo[]>([
		{
			value: 'default',
			label: t('default-device')
		}
	]);

	useEffect(() => {
		const list = audioOutput.map(item => ({ value: item.deviceId, label: item.label }));
		setSpeakerDevice([
			{
				value: 'default',
				label: t('default-device')
			},
			...list
		]);
		console.log(audioOutput);
	}, [audioOutput]);

	useEffect(() => {
		if (selectKey === '3') {
			createAnalyser();
		} else {
			stop();
		}
		return () => {
			stop();
		};
	}, [selectKey]);

	useEffect(() => {
		form.setFieldValue('speakerDeviceID', defaultDevice?.deviceId || 'default');
		setSelectedID(defaultDevice?.deviceId || 'default');
		console.log(defaultDevice);
		
	}, [defaultDevice]);

	const play = () => {
		if (audioAnalyserRef.current && defaultDevice?.deviceId) {
			audioAnalyserRef.current.setSinkId(defaultDevice?.deviceId);
		}

		if (audioRef.current) {
			audioRef.current.play();
			setPlay(true);
		}
	};

	const startTest = () => {
		if (isPlay) {
			stop();
		} else {
			play();
		}
	};

	const createAnalyser = () => {
		if (!audioRef.current) return;
		if (audioAnalyserRef.current) return;

		audioAnalyserRef.current = new AudioAnalyser(audioRef.current, false);
		audioAnalyserRef.current.createAnalyser((level: number) => form.setFieldValue('outputVol', level));
	};

	const stop = () => {
		if (audioRef.current) {
			audioRef.current.pause();
			setPlay(false);
		}
	};

	const selectSpeaker = async (value: string) => {
		const output = audioOutput.find(item => item.groupId === defaultDevice?.groupId);
		if (audioAnalyserRef.current) {
			try {
				if (value !== 'default') {
					audioAnalyserRef.current.setSinkId(value);
				} else {
					if (output) {
						audioAnalyserRef.current.setSinkId(output.deviceId);
					}
				}
			} catch (error) {
				console.error('select speaker error', error);
			}
		}
		onSelect(value);
	};

	const valueChangeHandler = (values: any) => {
		if (values.speakerVol !== undefined) {
			if (audioRef.current) {
				audioRef.current.volume = values.speakerVol / 100;
			}
		}
	};

	const ok = () => {
		stop();
		onOk();
	};

	const cancel = () => {
		stop();
		onCancel();
	};
	return (
		<>
			<Form labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} layout="horizontal" form={form} onValuesChange={valueChangeHandler} style={{ maxWidth: 700 }}>
				<Row>
					<Col span={16}>
						<Form.Item label={t('speaker')} name="speakerDeviceID" labelAlign="left" labelCol={{ span: 6 }}>
							<Select disabled={speakerDevice.length === 1} defaultValue={defaultDevice?.deviceId || 'default'} onChange={selectSpeaker}>
								{speakerDevice.map(item => (
									<Select.Option key={item.value} value={item.value}>
										{item.label}
									</Select.Option>
								))}
							</Select>
						</Form.Item>
					</Col>
					<Col span={8} style={{ textAlign: 'center' }}>
						<Form.Item>
							<Button type="primary" onClick={startTest}>
								{isPlay ? t('stop-test') : t('test-speaker')}
							</Button>
						</Form.Item>
					</Col>
				</Row>

				<Form.Item label={t('output-level')} name="outputVol" labelAlign="left">
					<Slider defaultValue={0} handleStyle={{ display: 'none' }} />
				</Form.Item>
				<Form.Item label={t('vol')} name="speakerVol" labelAlign="left">
					<Slider defaultValue={speakerVol} min={0} max={100} />
				</Form.Item>
			</Form>
			<Submit>
				<Button type="default" onClick={cancel}>
					{t('cancel')}
				</Button>
				<Button type="primary" onClick={ok}>
					{t('sure')}
				</Button>
			</Submit>
			<audio ref={audioRef} src="./media/ring.wav" loop id="test-sperak-ring" style={{ visibility: 'hidden' }}></audio>
		</>
	);
};

export default SpeakerConfigure;
